import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import {getTimestamp} from './auth'

const exporess_time = 30*60*1000
// const exporess_time = 10*1000

const instance = axios.create({
  baseURL: process.env.VUE_APP_BASEURL
})
//请求拦截器
instance.interceptors.request.use(
  config => {
    const currentTime = Date.now()
    const token_time = getTimestamp()
    const space = currentTime - token_time
    if (space > exporess_time) {
      store.dispatch('user/logout')
      Message({
        type: 'info',
        message: '登录失效，请重新登录'
      })
      router.push(`/login?_redirect=${window.location.href.split('#')[1]}`)
      return Promise.reject(new Error('登录失效，请重新登录'))
    }
    const token = store.getters.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
//响应拦截器
instance.interceptors.response.use(
  response => {
    const { success, message } = response.data
    if (success) {
      return response.data
    } else {
      Message({
        message: message,
        type: 'error'
      })
      return Promise.reject(new Error(message))
    }
  },
  error => {
    // console.dir(error);
    const bool = error.response && error.response.data && error.response.data.code === 10002
    if (bool) {
      store.dispatch('user/logout')
      const url = window.location.href.split('#')[1]
      router.push(`login?_redirect=${url}`)
    }
    return Promise.reject(error)
  }
)
export default instance
